﻿#region Usings
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using BK.Model;
using BK.Repositories.Abstract;
using BK.Repositories.Factory;

using Lib.Utils.WebUtils;
#endregion

namespace BK.Web.UI.HttpHandlers
{
    /// <summary>
    /// Summary description for CategoriesHandler
    /// </summary>
    public class CategoriesHandler : IHttpHandler
    {
        #region Readonly & Static Fields
        private readonly ICategoriesRepository _categoriesRepository =
            RepositoryFactory.Get<ICategoriesRepository>();
        #endregion

        #region IHttpHandler Members
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json;charset=UTF-8";
            IEnumerable<Category> categories = _categoriesRepository.GetBy(UserId);
            Dto[] entities = (from i
                                  in categories
                              orderby i.FullName
                              select new Dto {Text = i.FullName, Id = i.Id}).ToArray();

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (Dto[]));

            StringBuilder stringBuilder = new StringBuilder();
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.WriteObject(stream, entities);

                stream.Position = 0;
                StreamReader streamReader = new StreamReader(stream);
                stringBuilder.Append(streamReader.ReadToEnd());
            }

            context.Response.Write(stringBuilder.ToString());
            context.Response.End();
        }

        public bool IsReusable
        {
            get { return false; }
        }
        #endregion

        #region Class Properties
        private static int UserId
        {
            get { return RequestManager.GetValue<int>("UserId", -1); }
        }
        #endregion
    }
}